CC= g++
#		-fno-strict-aliasing \

#		-Werror \

CFLAGS=	\
		-Wall \
		-D_REENTRANT \
		-D_GNU_SOURCE \
		-funsigned-char \

CFLAGS+=	-rdynamic	# for glibc's function backtrace_symbols


INC=		-Iinclude \


LIBS=		\


ifdef WITH_DEBUG
CFLAGS+=	-O0 -g3 -ggdb3 -DDEBUG -DMALLOC_DEBUG
else
# Optimization makes server fall down (-O2, -O3)
CFLAGS+=	-O0
endif


ifdef WITH_PROFILE
#CFLAGS+=	--coverage
CFLAGS+=	-pg -g -fprofile-arcs -ftest-coverage
#LIBS+=		--coverage
#LIBS+=		-lprofiler -ltcmalloc
endif


SRCS=		\
		Parser.cpp \


.PHONY: optimized debug profile all clean clean-all


optimized:
	$(MAKE) all


debug:
	$(MAKE) all WITH_DEBUG=1


profile:
	$(MAKE) all WITH_DEBUG=1 WITH_PROFILE=1


all: main $(addprefix unittest/, $(SRCS:.cpp=)) $(addprefix unittest/.libs/, $(SRCS:.cpp=.ok))
	@echo ""
	@echo "DONE"
	@echo ""


# linking main
main: src/.libs/main.o $(addprefix src/.libs/, $(SRCS:.cpp=.o))
	@echo "Linking $@:"
	$(CC) $(CFLAGS) $(LIBS) $+ -o $@
	@echo "--------------------------------------------------"


# tests execution
unittest/.libs/%.ok: unittest/%
	@echo -n "Testing $+:    "
	-@`./$+` && echo -e "OK" && touch $@


# linking tests
unittest/%: src/.libs/%.unittest.o src/.libs/%.o
	@echo "Linking $@:"
	$(CC) $(CFLAGS) $(LIBS) $+ -o $@
	@echo "--------------------------------------------------"


# collecting src deps
-include $(addprefix src/.libs/, $(SRCS:.cpp=.d))
src/.libs/%.d: src/%.cpp $(wildcard include/*)
	@gcc -MM -MF $(@D)/$(@F) -MT $(@D)/$(@F:.d=.o) $(INC) $(@D)/../$(@F:.d=.cpp)


# tests deps collecting
-include $(addprefix src/.libs/, $(SRCS:.cpp=.unittest.d))
src/.libs/%.unittest.d: $(wildcard include/*)
	@gcc -MM -MF $(@D)/$(@F) -MT $(@D)/$(@F:.d=.o) $(INC) $(@D)/../$(@F:.d=.cpp)


# src objects building
src/.libs/%.o: src/%.cpp
	@echo "Building $@:"
	$(CC) $(CFLAGS) $(INC) -c $(<D)/$(<F) -o $(@D)/$(@F)
	@echo "--------------------------------------------------"


clean:
	$(RM) \
		src/.libs/*.o \
		src/.libs/*.gcno \
		src/.libs/*.gcda \
		src/.libs/*.gcov \
		unittest/.libs/*.ok \
		unittest/* \


clean-all: clean
#	$(MAKE) clean

	$(RM) \
		src/.libs/*.d \
		main \

